package org.grayrabbit.cms.service.lucene.impl;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.document.DateTools;
import org.apache.lucene.document.DateTools.Resolution;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TermRangeQuery;
import org.apache.lucene.search.TopScoreDocCollector;
import org.apache.lucene.search.WildcardQuery;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.SimpleFragmenter;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.apache.lucene.search.highlight.TokenSources;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.LockObtainFailedException;
import org.apache.lucene.util.Version;
import org.grayrabbit.cms.constant.DictionaryStaticValues;
import org.grayrabbit.cms.dao.category.CategoryDao;
import org.grayrabbit.cms.dao.content.ContentDao;
import org.grayrabbit.cms.dao.site.SiteDao;
import org.grayrabbit.cms.dao.topic.TopicDao;
import org.grayrabbit.cms.entity.Category;
import org.grayrabbit.cms.entity.Content;
import org.grayrabbit.cms.entity.Site;
import org.grayrabbit.cms.entity.Topic;
import org.grayrabbit.cms.service.lucene.SearchLuceneService;
import org.grayrabbit.cms.util.FilePathSptUtil;
import org.grayrabbit.cms.util.lucene.AnalyzerUtil;
import org.grayrabbit.cms.util.lucene.LuceneUtil;
import org.grayrabbit.cms.vo.lucene.LuceneBean;
import org.grayrabbit.cms.vo.lucene.SearchConditionBean;
import org.grayrabbit.cms.vo.site.SiteBean;
import org.grayrabbit.dao.util.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.wltea.analyzer.lucene.IKQueryParser;
import org.wltea.analyzer.lucene.IKSimilarity;

@Service
@Transactional
public class SearchLuceneServiceImpl implements SearchLuceneService {
	private final static Logger logger = LoggerFactory.getLogger(SearchLuceneServiceImpl.class);
	private final static int MAX_INDEX_COUNT = 500;
	/**显示文字长度*/
	private final static int MAX_CONTENT_LENGTH=100;
	
	private final static String CONTENT_PATH = FilePathSptUtil.LUCENE_INDEX + File.separator + "content";
	
	private final static String HTML_PATH =  FilePathSptUtil.LUCENE_INDEX + File.separator + "html";
	
	private final static String INDEX_PATH =  FilePathSptUtil.LUCENE_INDEX + File.separator + "search";
	
	@Autowired
	@Qualifier("contentDaoImpl")
	private ContentDao contentDao;

	@Autowired
	@Qualifier("topicDaoImpl")
	private TopicDao topicDao;

	@Autowired
	@Qualifier("categoryDaoImpl")
	private CategoryDao categoryDao;

	@Autowired
	@Qualifier("siteDaoImpl")
	private SiteDao siteDao;

	public void createAllIndex() {
		mergerIndex(createHtmlIndex(), createContentIndex());
	}

	public boolean createContentIndex() {
		IndexWriter indexWriter = null;
		Directory d = null;
		try {
			d = FSDirectory.open(deleteIndex(CONTENT_PATH));
			IndexWriterConfig conf = new IndexWriterConfig(Version.LUCENE_31, AnalyzerUtil.getIkAnalyzer());
			// 创建索引模式：CREATE，覆盖模式； APPEND，追加模式
			conf.setOpenMode(IndexWriterConfig.OpenMode.CREATE);
			indexWriter = new IndexWriter(d, conf);
			int count = contentDao.countPublishContent(null ,null);
			int i = 0;
			List<Content> list = null;
			while (count > 0) {
				list = contentDao.ListPublishContent(i*MAX_INDEX_COUNT, MAX_INDEX_COUNT, null,null);
				i++;			
				for (Content c : list) {
					Category category = null;
					Topic topic = null;
					Site site = null;
					if (c.getCategory() != null && StringUtils.isNotBlank(c.getCategory().getCategoryId())) {
						category = categoryDao.findById(c.getCategory().getCategoryId());
						categoryDao.initialize(category);
						categoryDao.initialize(category.getSite());
						site = category.getSite();
						
					} else if (c.getTopic() != null && StringUtils.isNotBlank(c.getTopic().getTopicId())) {
						topic = topicDao.findById(c.getTopic().getTopicId());
						topicDao.initialize(topic);
						topicDao.initialize(topic.getSite());
						site = topic.getSite();
					}
					try {
						if(category!=null){
							String ids = categoryIds(category.getCategoryId());
							Document doc = LuceneUtil.getDocument(c, site, ids,category.getCatName(), topic);
							indexWriter.addDocument(doc);
						}
						else{
							Document doc = LuceneUtil.getDocument(c, site, "","", topic);
							indexWriter.addDocument(doc);
						}
						
					} catch (Exception e) {
						e.printStackTrace();
						logger.error("异常数据:{}",c.getContentId());
						logger.error(e.getMessage());
					}

				}
				count = count - MAX_INDEX_COUNT;
				list.clear();
				contentDao.clear();
				logger.debug("当前共有索引{}个", indexWriter.numDocs());
				Thread.sleep(100);
			}
			logger.debug("索引结束,共有索引{}个", indexWriter.numDocs());
			// 自动优化合并索引文件
			indexWriter.optimize();
			indexWriter.commit();
			return true;
		} catch (CorruptIndexException e) {
			e.printStackTrace();
			logger.error("索引添加异常", e);
		} catch (LockObtainFailedException e) {
			e.printStackTrace();
			logger.error("索引添加异常", e);
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("索引不存在", e);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("索引添加异常", e);
		} finally {
			if (indexWriter != null) {
				try {
					indexWriter.close();
				} catch (CorruptIndexException e) {
					e.printStackTrace();
					logger.error("索引关闭异常", e);
				} catch (IOException e) {
					e.printStackTrace();
					logger.error("索引关闭异常", e);
				} finally {
					try {
						if (d != null && IndexWriter.isLocked(d)) {
							IndexWriter.unlock(d);
						}
					} catch (IOException e) {
						e.printStackTrace();
						logger.error("解锁异常", e);
					}
				}
			}
		}
		return false;
	}

	public boolean createHtmlIndex() {		
		IndexWriter indexWriter = null;
		Directory d = null;
		try {
			d = FSDirectory.open(deleteIndex(HTML_PATH));
			IndexWriterConfig conf = new IndexWriterConfig(Version.LUCENE_31, AnalyzerUtil.getIkAnalyzer());
			// 创建索引模式：CREATE，覆盖模式； APPEND，追加模式
			conf.setOpenMode(IndexWriterConfig.OpenMode.CREATE);
			indexWriter = new IndexWriter(d, conf);
			SiteBean bean = new SiteBean();
			bean.setSiteStatus(true);

			int i = 0;
			Page<Site> page = new Page<Site>();
			page.setPageSize(MAX_INDEX_COUNT);
			int count = siteDao.count(bean);
			List<Site> list = null;
			while (count > 0) {
				page.setPageNo(i++);
				list = siteDao.findByPage(page, bean);
				for (Site site : list) {
					String folder =FilePathSptUtil.LOCAL_SITE_PUBLISH_PATH+File.separator+site.getSiteShortName()+File.separator;
					try {
						File index = new File(folder + "index.html");
						if (index.exists()) {
							Document doc = LuceneUtil.getDocument(index, "index.html", site);
							indexWriter.addDocument(doc);
						}
						File fc = new File(folder + DictionaryStaticValues.CATEGORY);
						if (fc.exists() && fc.isDirectory()) {
							this.visitFiles(fc, indexWriter, DictionaryStaticValues.CATEGORY, site);
						}
						File ft = new File(folder + DictionaryStaticValues.TOPIC);
						if (ft.exists() && ft.isDirectory()) {
							this.visitFiles(ft, indexWriter, DictionaryStaticValues.TOPIC, site);
						}
					} catch (Exception e) {
						e.printStackTrace();
						logger.error(e.getMessage());
					}

				}
				count = count - MAX_INDEX_COUNT;
				list.clear();
				contentDao.clear();
				logger.debug("当前共有索引{}个", indexWriter.numDocs());
				Thread.sleep(100);
			}
			logger.debug("索引结束,共有索引{}个", indexWriter.numDocs());
			// 自动优化合并索引文件
			indexWriter.optimize();
			indexWriter.commit();
			return true;
		} catch (CorruptIndexException e) {
			e.printStackTrace();
			logger.error("索引添加异常", e);
		} catch (LockObtainFailedException e) {
			e.printStackTrace();
			logger.error("索引添加异常", e);
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("索引不存在", e);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("索引添加异常", e);
		} finally {
			if (indexWriter != null) {
				try {
					indexWriter.close();
				} catch (CorruptIndexException e) {
					e.printStackTrace();
					logger.error("索引关闭异常", e);
				} catch (IOException e) {
					e.printStackTrace();
					logger.error("索引关闭异常", e);
				} finally {
					try {
						if (d != null && IndexWriter.isLocked(d)) {
							IndexWriter.unlock(d);
						}
					} catch (IOException e) {
						e.printStackTrace();
						logger.error("解锁异常", e);
					}
				}
			}
		}
		return false;
	}



	public void mergerIndex(boolean addHtml,boolean addContent) {
		logger.debug("正在合并索引{}",System.currentTimeMillis());
		File file = null;
		if(addContent&&addHtml){
			file = deleteIndex(INDEX_PATH);
		}
		else{
			file = new File(INDEX_PATH);;
		}
		
		Directory d = null;
		IndexWriter indexWriter = null;
		try {
			d = FSDirectory.open(file);
			if(!file.exists()){
				file.mkdirs();
			}
			while(d!=null&&IndexWriter.isLocked(d)){//如果文件锁住,等待解锁后合并
				Thread.sleep(2000);
				logger.error("合并索引已经锁住，正在等待....");
			}
			IndexWriterConfig conf = new IndexWriterConfig(Version.LUCENE_31, AnalyzerUtil.getIkAnalyzer());
			// 创建索引模式：CREATE，覆盖模式； APPEND，追加模式
			conf.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);
			indexWriter = new IndexWriter(d, conf);			
			if(addContent){
				Term term = new Term(LuceneUtil.ENTITYNAME, "content");
				indexWriter.deleteDocuments(term);
				indexWriter.addIndexes(FSDirectory.open(new File(CONTENT_PATH)));		
			}
			if(addHtml){
				Term term = new Term(LuceneUtil.TYPE, LuceneUtil.TYPE_HTML);
				indexWriter.deleteDocuments(term);
				indexWriter.addIndexes(FSDirectory.open(new File(HTML_PATH)));		
			}
			logger.debug("合并索引结束{}",System.currentTimeMillis());
			logger.debug("共有索引{}个", indexWriter.numDocs());
			// 自动优化合并索引文件
			indexWriter.optimize();
			indexWriter.commit();
			indexWriter.close();
		}
		catch (CorruptIndexException e) {
			e.printStackTrace();
			logger.error("索引合并异常", e);
		} catch (LockObtainFailedException e) {
			e.printStackTrace();
			logger.error("索引合并异常", e);
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("索引不存在", e);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("索引合并异常", e);
		} finally {
			if (indexWriter != null) {
				try {
					indexWriter.close();
				} catch (CorruptIndexException e) {
					e.printStackTrace();
					logger.error("索引关闭异常", e);
				} catch (IOException e) {
					e.printStackTrace();
					logger.error("索引关闭异常", e);
				} finally {
					try {
						if (d != null && IndexWriter.isLocked(d)) {
							IndexWriter.unlock(d);
						}
					} catch (IOException e) {
						e.printStackTrace();
						logger.error("解锁异常", e);
					}
				}
			}
		}
	}

	private void visitFiles(File filePath, IndexWriter indexWriter, String path, Site site) throws Exception {
		File[] fs = filePath.listFiles();
		logger.debug("{}文件个数{}", filePath.getPath(), fs.length);
		for (int i = 0; i < fs.length; i++) {
			if (fs[i].exists() && fs[i].isDirectory()) {
				logger.debug("文件夹{}", fs[i].getPath());
				visitFiles(new File(filePath + File.separator + fs[i].getName()), indexWriter, path + "/" + fs[i].getName(), site);
			} else {
				logger.debug("建立索引{}", fs[i].getPath());
				Document doc = LuceneUtil.getDocument(fs[i], path + "/" + fs[i].getName(), site);
				indexWriter.addDocument(doc);
			}
		}

	}
	private File deleteIndex(String path){
		File file = new File(path);
		if (file.exists()) {
			if (file.isFile()) {
				file.delete();
			} else {
				File[] f = file.listFiles();
				for (int i = 0; i < f.length; i++) {
					f[i].delete();
				}
			}
		} else {
			file.mkdirs();
		}
		return file;
	}

	
	public List<LuceneBean> search(SearchConditionBean scb, Page<LuceneBean> page) throws Exception {
		IndexReader reader = null;
		try {
			BooleanQuery query = new BooleanQuery();
			reader = IndexReader.open(FSDirectory.open(new File(INDEX_PATH)));
			IndexSearcher searcher = new IndexSearcher(reader);
			// 在索引器中使用IKSimilarity相似度评估器
			searcher.setSimilarity(new IKSimilarity());
			BooleanQuery bqkw = new BooleanQuery();
			if(scb.getFuzzy()!=null&&!scb.getFuzzy()&&StringUtils.isNotBlank(scb.getKeywords())){//精确查找
				query.add(IKQueryParser.parse(LuceneUtil.TITLE,scb.getKeywords()), Occur.MUST);
			}
			else{
				if(StringUtils.isBlank(scb.getKeywords())){
					query.add(MultiFieldQueryParser.parse(Version.LUCENE_31, "*:*", new String[]{LuceneUtil.TITLE}, new Occur[]{Occur.SHOULD}, AnalyzerUtil.getIkAnalyzer()),Occur.SHOULD);
				}
				//标题和内容
				else if(scb.getQueryField()==null||scb.getQueryField().compareTo(0)==0){
					//空格变为与
					String[] kws = scb.getKeywords().trim().split(" ");
					if(kws.length>1){
						for(String kw:kws){
							Query kq = IKQueryParser.parseMultiField(new String[]{LuceneUtil.TITLE,LuceneUtil.CONTENT}, kw, new Occur[]{Occur.SHOULD,Occur.SHOULD});
							bqkw.add(kq, Occur.MUST);
						}
						query.add(bqkw, Occur.MUST);
					}
					else{
						bqkw.add(IKQueryParser.parseMultiField(new String[]{LuceneUtil.TITLE,LuceneUtil.CONTENT}, scb.getKeywords(), new Occur[]{Occur.SHOULD,Occur.SHOULD}),Occur.MUST);
						query.add(IKQueryParser.parseMultiField(new String[]{LuceneUtil.TITLE,LuceneUtil.CONTENT}, scb.getKeywords(), new Occur[]{Occur.SHOULD,Occur.SHOULD}),Occur.MUST);
					}
				}
				//标题
				else if(scb.getQueryField().compareTo(1)==0){
					String[] kws = scb.getKeywords().trim().split(" ");
					if(kws.length>1){
						BooleanQuery bq = new BooleanQuery();
						for(String kw:kws){
							bq.add(IKQueryParser.parse(LuceneUtil.TITLE,kw), Occur.MUST);
						}
						query.add(bq, Occur.MUST);
					}
					else{
						query.add(IKQueryParser.parse(LuceneUtil.TITLE, scb.getKeywords()), Occur.MUST);
					}
				}
				//内容
				else if(scb.getQueryField().compareTo(2)==0){		
					String[] kws = scb.getKeywords().trim().split(" ");
					if(kws.length>1){
						BooleanQuery bq = new BooleanQuery();
						for(String kw:kws){
							bq.add(IKQueryParser.parse(LuceneUtil.CONTENT,kw), Occur.MUST);
						}
						query.add(bq, Occur.MUST);
					}
					else{
						query.add(IKQueryParser.parse(LuceneUtil.CONTENT, scb.getKeywords()), Occur.MUST);
					}
				}
			}
			
			
			//栏目搜索
			if(scb.getCategoryid()!=null&&scb.getCategoryid().length>0){
				BooleanQuery booleanquery = new BooleanQuery();
				for (String category : scb.getCategoryid()) {
					Term t = new Term(LuceneUtil.CATEGORYID,"*"+category+"*"); 
					WildcardQuery q = new WildcardQuery(t); 
					booleanquery.add(q, Occur.SHOULD);
				}
				query.add(booleanquery, Occur.MUST);
			}
			
			if(scb.getSiteid()!=null&&scb.getSiteid().length>0){
				BooleanQuery booleanquery = new BooleanQuery();
				for (String id : scb.getSiteid()) {
					Query termquery = new TermQuery(new Term(LuceneUtil.SITEID, id));
					booleanquery.add(termquery, Occur.SHOULD);
				}
				query.add(booleanquery, Occur.MUST);
			}
			
			if(StringUtils.isNotBlank(scb.getNotKeyword())){//不包含关键字
				if(scb.getQueryField()==null||scb.getQueryField().compareTo(0)==0){
					//空格变为与
					String[] kws = scb.getNotKeyword().trim().split(" ");
					if(kws.length>1){
						BooleanQuery bq = new BooleanQuery();
						for(String kw:kws){
							Query kq = IKQueryParser.parseMultiField(new String[]{LuceneUtil.TITLE,LuceneUtil.CONTENT}, kw, new Occur[]{Occur.SHOULD,Occur.SHOULD});
							bq.add(kq, Occur.SHOULD);
						}
						query.add(bq, Occur.MUST_NOT);
					}
					else{
						query.add(IKQueryParser.parseMultiField(new String[]{LuceneUtil.TITLE,LuceneUtil.CONTENT}, scb.getNotKeyword(), new Occur[]{Occur.SHOULD,Occur.SHOULD}),Occur.MUST_NOT);
					}
				}
				//标题
				else if(scb.getQueryField().compareTo(1)==0){
					String[] kws = scb.getNotKeyword().trim().split(" ");
					if(kws.length>1){
						BooleanQuery bq = new BooleanQuery();
						for(String kw:kws){
							bq.add(IKQueryParser.parse(LuceneUtil.TITLE,kw), Occur.SHOULD);
						}
						query.add(bq, Occur.MUST_NOT);
					}
					else{
						query.add(IKQueryParser.parse(LuceneUtil.TITLE, scb.getNotKeyword()), Occur.MUST_NOT);
					}
				}
				//内容
				else if(scb.getQueryField().compareTo(2)==0){		
					String[] kws = scb.getNotKeyword().trim().split("\\s{1,}");
					if(kws.length>1){
						BooleanQuery bq = new BooleanQuery();
						for(String kw:kws){
							bq.add(IKQueryParser.parse(LuceneUtil.CONTENT,kw), Occur.SHOULD);
						}
						query.add(bq, Occur.MUST_NOT);
					}
					else{
						query.add(IKQueryParser.parse(LuceneUtil.CONTENT, scb.getNotKeyword()), Occur.MUST_NOT);
					}
				}			
			}
			
			//日期过滤
			if(scb.getBegDate()!=null||scb.getEndDate()!=null){
				String start = null;
				String end = null;
				if(scb.getBegDate()!=null){
					start = DateTools.dateToString(scb.getBegDate(), Resolution.SECOND);
				}
				if(scb.getEndDate()!=null){
					end = DateTools.dateToString(scb.getEndDate(), Resolution.SECOND);
				}
				Query q = new TermRangeQuery(LuceneUtil.DATE, start, end, true, true);
				query.add(q,Occur.MUST);
			}
			//类型    栏目5 | 答疑 4 | 企业 3 |  产品 2 | 文章 1 | 全部	0 null
			if(scb.getContentType()!=null){
				if(scb.getContentType().intValue()==1){
					Term t = new Term(LuceneUtil.ENTITYNAME, "content");
					query.add(new TermQuery(t),Occur.MUST);
				}
				else if(scb.getContentType().intValue()==2){
					Term t = new Term(LuceneUtil.ENTITYNAME, "product");
					query.add(new TermQuery(t),Occur.MUST);
				}
				else if(scb.getContentType().intValue()==3){
					Term t = new Term(LuceneUtil.ENTITYNAME, "enterprise");
					query.add(new TermQuery(t),Occur.MUST);
				}
				else if(scb.getContentType().intValue()==4){
					Term t = new Term(LuceneUtil.ENTITYNAME, "taxQuestion");
					query.add(new TermQuery(t),Occur.MUST);
				}
				else if(scb.getContentType().intValue()==5){
					Term t = new Term(LuceneUtil.TYPE, LuceneUtil.TYPE_HTML);
					query.add(new TermQuery(t),Occur.MUST);
				}
			}
			logger.debug("QUERY:{}",query.toString());
			return getList(query,bqkw , page, searcher);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			throw e;
		}
		finally{
			if(reader!=null){
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
					logger.error("Reader 关闭异常", e);
				}
			}
		}
	}
	
	
	/**
	 * Content 转换
	 * @throws Exception 
	 */
	private List<LuceneBean> getList(Query query,BooleanQuery bqkw , Page<LuceneBean> page, IndexSearcher searcher) throws Exception {
		TopScoreDocCollector topCollector = TopScoreDocCollector.create(searcher.maxDoc(), false);
		searcher.search(query, topCollector);		
		SimpleHTMLFormatter simpleHtmlFormatter = new SimpleHTMLFormatter("<font color='red'>", "</font>");// 高亮
		Highlighter highlighter = new Highlighter(simpleHtmlFormatter, new QueryScorer(bqkw));
		highlighter.setTextFragmenter(new SimpleFragmenter(MAX_CONTENT_LENGTH));
		page.setTotal(topCollector.getTotalHits());
		ScoreDoc[] docs = topCollector.topDocs((page.getPageNo() - 1) * page.getPageSize(), page.getPageSize()).scoreDocs;
		List<LuceneBean> list = new ArrayList<LuceneBean>();
		for (ScoreDoc scdoc : docs) {
			Document document = searcher.doc(scdoc.doc);
			TokenStream tokenStream = TokenSources.getAnyTokenStream(searcher.getIndexReader(), scdoc.doc, LuceneUtil.CONTENT, AnalyzerUtil.getIkAnalyzer());
			TokenStream titletokenStream = TokenSources.getAnyTokenStream(searcher.getIndexReader(), scdoc.doc, LuceneUtil.TITLE, AnalyzerUtil.getIkAnalyzer());
			String title = document.get(LuceneUtil.TITLE);
			
			String context = document.get(LuceneUtil.CONTENT);
			String content = highlighter.getBestFragment(tokenStream, context);
			String title_c = highlighter.getBestFragment(titletokenStream, title);
			LuceneBean lb = new LuceneBean();
			try{
				lb.setId(document.get(LuceneUtil.DBID));
				lb.setEntityName(document.get(LuceneUtil.ENTITYNAME));
				lb.setUrl(document.get(LuceneUtil.URL));
				if(StringUtils.isNotBlank(title_c)){
					lb.setTitle(title_c);
				}
				else{
					lb.setTitle(title);
				}
				
				lb.setType(document.get(LuceneUtil.TYPE));
				lb.setContent(document.get(LuceneUtil.CONTENT));
				if (StringUtils.isNotBlank(content)) {
					lb.setContent(content);
				} else {
					lb.setContent(context.length() > MAX_CONTENT_LENGTH ? context.substring(0, MAX_CONTENT_LENGTH) : context);
				}
				lb.setDate(DateTools.stringToDate(document.get(LuceneUtil.DATE)));
				lb.setSiteId(document.get(LuceneUtil.SITEID));
				lb.setSiteName(document.get(LuceneUtil.SITENAME));
				lb.setSource(document.get(LuceneUtil.SOURCE));
				lb.setAuthor(document.get(LuceneUtil.AUTHOR));
				lb.setCategoryName(document.get(LuceneUtil.CATEGOEYNAME));
				lb.setCategoryId(document.get(LuceneUtil.CATEGORYID));
				lb.setTopicId(document.get(LuceneUtil.TOPICID));
				lb.setTopicName(document.get(LuceneUtil.TOPICNAME));
				lb.setContentType(document.get(LuceneUtil.CONTENTTYPE));
				list.add(lb);
			}
			catch (Exception e) {
				throw new Exception("Document->LuceneBean 转换异常", e);
			}
					
		}
		page.setResult(list);
		return list;
	}
	
	public String categoryIds(String catId) {		
		try{
			Category cat = categoryDao.findById(catId);
			categoryDao.initialize(cat);
			StringBuffer sb = new StringBuffer();
			sb.append(cat.getCategoryId());
			while(cat!=null && cat.getCategory()!=null&&StringUtils.isNotBlank(cat.getCategory().getCategoryId())){
				cat = categoryDao.findById(cat.getCategory().getCategoryId());
				categoryDao.initialize(cat);
				sb.insert(0,cat.getCategoryId()+" ");
			} 
			return sb.toString();
		}catch(Exception e){
			logger.error("获取栏目异常",e);
		}
		return catId;
	}
		
}
